package easy.springmvc.servlet;

import com.alibaba.fastjson.JSON;
import easy.springmvc.annotation.MyEasyAutowired;
import easy.springmvc.annotation.MyEasyController;
import easy.springmvc.annotation.MyEasyRequestMapping;
import easy.springmvc.annotation.MyEasyRequestParam;
import easy.springmvc.annotation.MyEasyService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;


/**
 *
 *         2.1、加载配置文件

 *         2.2、扫描用户配置包下面所有的类

 *         2.3、拿到扫描到的类，通过反射机制，实例化。并且放到ioc容器中(Map的键值对  beanName-bean) beanName默认是首字母小写

 *         2.4、初始化HandlerMapping，这里其实就是把url和method对应起来放在一个k-v的Map中,在运行阶段取出


 */
public class MyEasyDispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String /*classSimpleName*/, Object /*Class instance*/> ioc = new HashMap<>();

    private Map<String /*url*/, Method> handlerMapping = new  HashMap<>();

    private Map<String /*url*/, Object> controllerMap  =new HashMap<>();



    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.初始化所有相关联的类,扫描用户设定的包下面所有的类
        String packageName = properties.getProperty("scanPackage");
        System.out.println("MyEasyDispatcherServlet.doScanner packageName: "+packageName);
        doScanner(packageName);

        //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
        doInstance();

        // 4.实例化Spring中的依赖注入
        doAutowired();

        //5.初始化HandlerMapping(将url和method对应上)
        initHandlerMapping();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        String method = req.getMethod();
        System.out.println("MyEasyDispatcherServlet.doGet, url : "+url+", contextPath: "+contextPath+", method: "+method);

        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String url = req.getRequestURI();
            String contextPath = req.getContextPath();
            String method = req.getMethod();
            System.out.println("MyEasyDispatcherServlet.doPost, url : "+url+", contextPath: "+contextPath+", method: "+method);


            //处理请求
            doDispatch(req,resp);
        } catch (Exception e) {
            resp.getWriter().write("500!! Server Exception");
        }
    }


    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if (handlerMapping.isEmpty()) {
            return;
        }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();// /MyEasySpringMVC,
        String methodStr = req.getMethod();// GET POST
        System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url+", contextPath: "+contextPath+", req method: "+methodStr);

        url = url.replace(contextPath, "").replaceAll("/+", "/");
        System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url);

        if (!this.handlerMapping.containsKey(url) || "/favicon.ico".equals(url)) {
            resp.getWriter().write("404 NOT FOUND!");
            return;
        }

        Method method = this.handlerMapping.get(url);
        System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url+", method: "+   method.getDeclaringClass() +"."+ method.getName());

        //获取方法的参数列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url+", parameterTypes: "+   JSON.toJSONString(parameterTypes));

        //获取请求的参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url+", parameterMap: "+   JSON.toJSONString(parameterMap));

        //保存参数值
        Object [] paramValues = new Object[parameterTypes.length];

        //方法的参数列表
        for (int i = 0; i<parameterTypes.length; i++){
            //根据参数名称，做某些处理
            String requestParam = parameterTypes[i].getSimpleName();

            if (requestParam.equals("HttpServletRequest")){
                //参数类型已明确，这边强转类型
                paramValues[i] = req;
                continue;
            }
            if (requestParam.equals("HttpServletResponse")){
                paramValues[i] = resp;
                continue;
            }
            /*if(requestParam.equals("String")){
                for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
                    String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                    paramValues[i]=value;
                }
            }*/
        }

        //获取请求中的集合
        for(Map.Entry<String,String[]> entry : parameterMap.entrySet()){
            String value = entry.getValue()[0];
            String name = entry.getKey();
            int index = hasRequestParam(method, name);
            // ===hasRequestParam===请求参数是：param========hhh, index= 2
            System.out.println("===hasRequestParam===请求参数是： ,name= " + name + ", value= " + value+", index= "+index);

            if(index != -1){
                paramValues[index] = value;
            }else {
                List<String> names = getparamterNames(method);
                System.out.println("===getparamterNames===请求参数是：names="+names+"  ,name= " + name + ", value= " + value+", index= "+index);
                for(int i = 0; i < names.size(); i ++){
                    if(name.equals(names.get(i))){
                        paramValues[i] = value;
                        break;
                    }
                }
            }
        }

        //利用反射机制来调用
        try {
            System.out.println("MyEasyDispatcherServlet.doDispatch, url : "+url+", contextPath: "+contextPath+", " +
                    "利用反射机制来调用 : method: "+  method.getDeclaringClass() +"."+ method.getName() +
                    " ， paramValues： "+ Arrays.asList(paramValues));
            method.invoke(this.controllerMap.get(url), paramValues);//第一个参数是method所对应的实例 在ioc容器中
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断控制器方法的参数，是否有RequestParam注解，且找到对应的value值，如果找到 返回这个参数的位置，如果没找到返回-1
     * @param method
     * @param name
     * @return
     */
    public int hasRequestParam(Method method, String name){
        Parameter[] parameters = method.getParameters();
        for(int i = 0; i < parameters.length; i ++){
            Parameter p = parameters[i];
            boolean b = p.isAnnotationPresent(MyEasyRequestParam.class);
            if(b){
                MyEasyRequestParam requestParam = p.getAnnotation(MyEasyRequestParam.class);
                String requestParamValue = requestParam.value();
                if(name.equals(requestParamValue)){
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 获取控制器方法的参数的名字
     * @param method
     * @return
     */
    public List<String> getparamterNames(Method method){
        List<String> list = new ArrayList<String>();
        Parameter[] parameters = method.getParameters();
        for(Parameter parameter : parameters){
            list.add(parameter.getName());
        }
        return list;
    }


    /**
     * 加载配置文件
     * @param location
     */
    private void  doLoadConfig(String location){
        System.out.println("加载配置文件");
        //把web.xml中的contextConfigLocation对应value值的文件加载到流里面
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            //用Properties文件加载文件里的内容
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关流
            if(null!=resourceAsStream){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            StringBuilder prop = new StringBuilder();
            Iterator<String> propNameSetIt = properties.stringPropertyNames().iterator();
            while (propNameSetIt.hasNext()){
                String key = propNameSetIt.next();
                Object value = properties.get(key);
                prop.append("key: ").append(key).append(" , value: ").append(String.valueOf(value)).append("\n");
            }
            System.out.println("加载配置文件完毕： "+prop.toString());

        }

    }


    /**
     * 初始化所有相关联的类,扫描用户设定的包下面所有的类
     * @param packageName
     */
    private void doScanner(String packageName) {
        //把所有的.替换成/
        URL url  = this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.", "/"));
        File dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if(file.isDirectory()){
                //递归读取包
                doScanner(packageName+"."+file.getName());
            }else{
                String className = packageName +"." +file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
        System.out.println("MyEasyDispatcherServlet.doScanner, classNames: "+ JSON.toJSONString(classNames));
    }


    /**
     * 拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
     */
    private void doInstance() {
        System.out.println("拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写");
        if (classNames.isEmpty()) {
            return;
        }
        for (String className : classNames) {
            try {
                // 读取类,通过反射来实例化(只有加@MyController需要实例化)
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(MyEasyController.class)){
                    String classSimpleName = toLowerFirstWord(clazz.getSimpleName());
                    Object beanInstance = clazz.newInstance();
                    ioc.put(toLowerFirstWord(classSimpleName), beanInstance);
                    //  ,beanInstance: "+beanInstance.toString()+
                    System.out.println("MyEasyDispatcherServlet.doInstance,【MyEasyController】 classSimpleName： "+classSimpleName+" ,beanInstance: "+beanInstance.toString());
                }else if(clazz.isAnnotationPresent(MyEasyService.class)){
                    MyEasyService annotation = clazz.getAnnotation(MyEasyService.class);
                    String beanName = annotation.value();
                    Object beanInstance = clazz.newInstance();
                    if (Objects.equals("", beanName)) {
                        // 多个接口
                        Class<?>[] interfaces = clazz.getInterfaces();
                        for(Class<?> c1 : interfaces){
                            String classSimpleName = toLowerFirstWord(c1.getSimpleName());
                            ioc.put(classSimpleName, beanInstance);
                            System.out.println("MyEasyDispatcherServlet.doInstance,【MyEasyService】 classSimpleName： "+classSimpleName+" ,beanInstance: "+beanInstance.toString());

                        }
                    }else {
                        ioc.put(beanName,beanInstance);
                    }
                }else{
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        Iterator<Map.Entry<String, Object>> iocItor = ioc.entrySet().iterator();
        while (iocItor.hasNext()){
            Map.Entry<String, Object> e = iocItor.next();
            String beanSimpleName = e.getKey();
            Object beanInstance = e.getValue();
            System.out.println("MyEasyDispatcherServlet.doInstance ,beanSimpleName: "+beanSimpleName+", beanInstance: "+beanInstance);
        }
        System.out.println("MyEasyDispatcherServlet.doInstance完成 ");

    }


    /**
     * 实例化Spring中的依赖注入
     */
    private void doAutowired(){
        System.out.println("实例化Spring中的依赖注入--doAutowired--，ioc.size(): "+ioc.size());
        if (ioc.size() ==0 ){
            return;
        }
        Iterator<Map.Entry<String, Object>> iocIter = ioc.entrySet().iterator();
        while (iocIter.hasNext()){
            //  /*classSimpleName*/, Object /*Class instance*/
            Map.Entry<String, Object> entry = iocIter.next();
            String classSimpleName = entry.getKey();
            Object beanInstance = entry.getValue();
            // FIXME :目前实现成员变量的依赖注入
            // TODO：后续处理构造器和方法
            Field[] declaredFields = beanInstance.getClass().getDeclaredFields();
            System.out.println("MyEasyDispatcherServlet.doAutowired, classSimpleName： "+classSimpleName+" ,beanInstance: "+beanInstance.toString()+", declaredFields  size: "+declaredFields.length+" : "+Arrays.asList(declaredFields));
            for (Field declaredField: declaredFields) {
                if (declaredField.isAnnotationPresent(MyEasyAutowired.class)){
                    declaredField.setAccessible(true);
                    MyEasyAutowired myEasyAutowired = declaredField.getAnnotation(MyEasyAutowired.class);
                    String autowiredBeanName = myEasyAutowired.value();
                    if (Objects.equals("",autowiredBeanName) || Objects.equals(null, autowiredBeanName)){
                        Class<?> declaredFieldType = declaredField.getType();
                        autowiredBeanName = toLowerFirstWord(declaredFieldType.getSimpleName());
                    }
                    System.out.println("MyEasyDispatcherServlet.doAutowired, classSimpleName： "+classSimpleName+" ,beanInstance:"+beanInstance+" , declaredField: "+declaredField.toString()+", declaredField.hashCode()： "+declaredField.hashCode()+", autowiredBeanName： "+autowiredBeanName+", autowiredBeanInstance: "+ioc.get(autowiredBeanName));
                    try {
                        Object helloService = declaredField.get(beanInstance);
                        System.out.println("declaredField:"+declaredField+", 反射get helloService: "+helloService+", beanInstance: "+beanInstance);

                        declaredField.setAccessible(true);
                        declaredField.set(beanInstance, ioc.get(autowiredBeanName));
                        helloService = declaredField.get(beanInstance);
                        System.out.println("declaredField:"+declaredField+", 反射set helloService: "+helloService+", beanInstance: "+beanInstance);

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 初始化HandlerMapping(将url和method对应上)
     */
    private void initHandlerMapping(){
        if(ioc.isEmpty()){
            return;
        }
        try {
            for (Map.Entry<String, Object> entry: ioc.entrySet()) {
                Class<? extends Object> clazz = entry.getValue().getClass();
                if(!clazz.isAnnotationPresent(MyEasyController.class)){
                    continue;
                }

                //拼url时,是controller头的url拼上方法上的url
                String baseUrl ="";
                String classSimpleName = "";
                Object beanInstance = null;
                if(clazz.isAnnotationPresent(MyEasyRequestMapping.class)){
                    MyEasyRequestMapping annotation = clazz.getAnnotation(MyEasyRequestMapping.class);
                    baseUrl = annotation.value();
                    classSimpleName = toLowerFirstWord(clazz.getSimpleName());
                    beanInstance = ioc.get(classSimpleName);
                }
                System.out.println("MyEasyDispatcherServlet.initHandlerMapping, baseUrl: "+ baseUrl+", classSimpleName: "+classSimpleName+", beanInstance: "+beanInstance);

                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if(!method.isAnnotationPresent(MyEasyRequestMapping.class)){
                        continue;
                    }
                    MyEasyRequestMapping annotation = method.getAnnotation(MyEasyRequestMapping.class);
                    String url = annotation.value();

                    url = (baseUrl+"/"+url).replaceAll("/+", "/");
                    if (handlerMapping.containsKey(url)){
                        throw new Exception(" Ambiguous url :"+url);
                    }
                    handlerMapping.put(url, method);
                    controllerMap.put(url, beanInstance);
                    System.out.println("MyEasyDispatcherServlet.initHandlerMapping========url: "+url+" ,method: "+method+", beanInstance: "+beanInstance.toString());
                }
            }
            System.out.println("MyEasyDispatcherServlet.initHandlerMapping完成, handlerMapping: "+ JSON.toJSONString(handlerMapping));
            System.out.println("MyEasyDispatcherServlet.initHandlerMapping完成, controllerMap: "+ JSON.toJSONString(controllerMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 把字符串的首字母小写
     * @param name
     * @return
     */
    public static String toLowerFirstWord(String name){
       /* char[] charArray = name.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);*/
        return name.substring(0,1).toLowerCase() + name.substring(1);
    }





}
